﻿using JdSoft.Apple.Apns.Notifications;
using Nmqtt;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace PushDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Push()
        {
            iOSPush();
            return View();
        }
        public ActionResult MqttPush()
        {
            AndroidPush();
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        /// <summary>
        /// iOS推送
        /// </summary>
        public void iOSPush()
        {

            //是否使用沙箱证书
            bool sandbox = true;

            //设备号
            string testDeviceToken = "ee22ec502267d132d28b30a3f6124815ffb60f4dea2a08a300e6cbe2812586bd";

            //证书
            string p12File = "./Content/slgh_apns_dev.p12";

            //证书密码
            string p12FilePassword = "jiuzhizun400";

            //消息数量
            int count = 1;

            string p12Filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);
            NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

            service.SendRetries = 5;
            service.ReconnectDelay = 5000;
            for (int i = 1; i <= count; i++)
            {
                Notification alertNotification = new Notification(testDeviceToken);

                alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);
                alertNotification.Payload.Sound = "default";
                alertNotification.Payload.Badge = i;
                bool falg = service.QueueNotification(alertNotification);
            }
            service.Close();
            service.Dispose();
        }
        /// <summary>
        /// Mqqt发送消息
        /// </summary>
        public void AndroidPush()
        {
            MqttClient sender = new MqttClient("192.168.1.121", "pc");
            //MqttClient sender = new MqttClient("mymqtt");
            //string[] topics = { "test" };
            //byte[] QOS_VALUES = { 0 };
            //sender.Subscribe(topics, QOS_VALUES);
            //sender.Connect();
            sender.PublishMessage("topicTest01", System.Text.Encoding.Default.GetBytes("this is pc test"));
        }

    }
}